package com.wsh.crawler.utils;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.Map;
import java.util.Random;

@Slf4j
@Component
public class HttpClientUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientUtil.class);

    private final HttpClient httpClient;
    private final Random random = new Random();

    // User-Agent池
//    private final String[] userAgents = {
//            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
//            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36",
//            "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36"
//    };
    private final String[] userAgents = {
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
            "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
    };

    public HttpClientUtil() {
        this.httpClient = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(10))
                .followRedirects(HttpClient.Redirect.NORMAL)
                .version(HttpClient.Version.HTTP_2)
                .build();
    }

    public String get(String url) throws Exception {
        // 随机延迟，避免被反爬
        Thread.sleep(random.nextInt(1000) + 500);

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .timeout(Duration.ofSeconds(30))
                .header("User-Agent", getRandomUserAgent())
                .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
                .header("Accept-Language", "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7")
//                .header("Accept-Encoding", "identity")
//                .header("Accept-Encoding", "gzip, deflate, br")
//                .header("Connection", "keep-alive")
                .GET()
                .build();

        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

        if (response.statusCode() == 200) {
            return response.body();
        } else {
            throw new RuntimeException("HTTP请求失败，状态码：" + response.statusCode());
        }
    }

    public String getWithHeaders(String url, Map<String, String> headers) {
        try {
            // 随机延迟，避免被反爬
            Thread.sleep(random.nextInt(1000) + 500);

            HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .timeout(Duration.ofSeconds(30))
                    .GET();

            // 添加自定义请求头
            for (Map.Entry<String, String> header : headers.entrySet()) {
                requestBuilder.header(header.getKey(), header.getValue());
            }

            // 添加默认请求头
            requestBuilder.header("Accept-Language", "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7");
            requestBuilder.header("Accept-Encoding", "identity");

            HttpRequest request = requestBuilder.build();
            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

            if (response.statusCode() == 200) {
                LOGGER.info("HTTP请求成功：{}", url);
                return response.body();
            } else {
                LOGGER.warn("HTTP请求失败，状态码：{}，URL：{}", response.statusCode(), url);
                return null;
            }

        } catch (Exception e) {
            LOGGER.error("HTTP请求失败：{}", url, e);
            return null;
        }
    }

    private String getRandomUserAgent() {
        return userAgents[random.nextInt(userAgents.length)];
    }
}